import os
import cv2
from myfun import read_pic,save_pic,check_dir,show_pic
import numpy as np
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ['KaiTi']
mpl.rcParams['font.serif'] = ['KaiTi']
mpl.rcParams['font.size'] =8
import matplotlib.pyplot as plt

def calRate(pic_img,file):
    # 显示图形
    pic_img = pic_img #// 257
    #print("pic_img:", pic_img, pic_img.shape)
    #show_pic(pic_img, file)

    # 图像做一下二值化操作 像素如果大于20，小于50的是我们石头的区域
    pic_1 = np.where(pic_img > 20*257, pic_img, 0)
    #print("pic_1:", pic_1, pic_1.shape)
    #show_pic(pic_1, "先把铁柱子变全黑")
    save_pic(pic_1,des1,file)

    pic_2 = np.where(pic_1 < 50*257, pic_1, 0)
    #print("pic2:的维度：", pic_2, pic_2.shape)
    #show_pic(pic_2.astype(np.uint8), "再把背景部分也变黑")
    save_pic(pic_2, des2, file)

    # 然后再来一遍二值化，如果背景是黑色的就是黑色的，其余的是白色的
    pic_3 = np.where(pic_2 > 1*257, 255*257, 0)
    #show_pic(pic_3.astype(np.uint8), "把石头部分变白，其余部分变黑")
    save_pic(pic_3, des3, file)

    # 这个时候需要进行（开运算，即先腐蚀后膨胀）的操作，完成一些竖着的线的去除
    kernel = np.ones((5, 5), np.uint8)
    pic_4 = cv2.morphologyEx(pic_3.astype(np.uint8),cv2.MORPH_OPEN, kernel).astype(np.uint8)
    #show_pic(pic_4, "腐蚀的效果")
    save_pic(pic_4, des4, file)

    contours, hierarchy = cv2.findContours(pic_4, cv2.RETR_EXTERNAL,
                                           cv2.CHAIN_APPROX_SIMPLE)  # cv2.RETR_EXTERNAL只检测外轮廓    cv2.CHAIN_APPROX_NONE存储所有边界点

    #print("contours:", len(contours))
    area_list = []
    for cnt in contours:
        x, y, w, h = cv2.boundingRect(cnt)
        cv2.rectangle(pic_4, (x, y), (x + w, y + h), (255, 255, 255), 1)
        area = float(w * h)
        #print(area)
        area_list.append(area)
    save_pic(pic_4, des5, file)

    return sum(area_list) / (pic_img.shape[0] * pic_img.shape[1])

src=r"F:\Python\PyWorkspace\陈裕涛\怡宝原图"
des1=r"F:\Python\PyWorkspace\陈裕涛\怡宝原图\1去掉黑色柱子"
des2=r"F:\Python\PyWorkspace\陈裕涛\怡宝原图\2把背景部分也变黑"
des3=r"F:\Python\PyWorkspace\陈裕涛\怡宝原图\3石头变白其余变黑"
des4=r"F:\Python\PyWorkspace\陈裕涛\怡宝原图\4开运算去掉杂质"
des5=r"F:\Python\PyWorkspace\陈裕涛\怡宝原图\5把外接矩形画上去"
check_dir(des1)
check_dir(des2)
check_dir(des3)
check_dir(des4)
check_dir(des5)

import pandas as pd
name=['图片名称','石头外接矩形面积占比']
df=pd.DataFrame(columns=name)

i=1
for file in os.listdir(src):
    if "tif" in file:
        #print(file,type(file))
        pic_img=read_pic(src,file)#原本图形的数值范围是0-65535，不好显示，现在转换为0-255 那就除以257
        #print(pic_img,pic_img.shape)
        rate=calRate(pic_img,file)
        df.loc[i]=[file,rate]
        i+=1

print(df)
df.to_csv("石头面积占比.csv",index=False)

